package cn.chl.controller;

import cn.chl.domain.Device;
import cn.chl.domain.Floor;
import cn.chl.dto.GetDeviceDto;
import cn.chl.result.JSONResult;
import cn.chl.service.IDeviceService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/device")
@RefreshScope // 动态刷新配置注解
public class DeviceController {

    @Autowired
    private IDeviceService deviceService;

    /**
     * 添加设备
     */
    @PostMapping("/add")
    public JSONResult add(@RequestBody Device device){
        deviceService.add(device);
        return new JSONResult(true,"添加成功");
    }

    /**
     * 查询设备信息localhost:8080/api/device/getDeviceInfoById?id=
     */
    @GetMapping("/getDeviceInfoById/{id}")
    @SentinelResource(value = "device-server",
            fallback = "fuseDegradation",
            blockHandler = "degradationMethod")
    public JSONResult getDeviceInfoById(@PathVariable("id") Integer id){
//        System.out.println(1/0);
        GetDeviceDto device = deviceService.getDeviceInfoById(id);
        return new JSONResult(true,"请求成功",device);
    }

    /**
     * 通过设备类型查询设备信息
     */
    @GetMapping("/getTypeById/{type}")
    public List<Device> getTypeById(@PathVariable("type") Integer type){
        return deviceService.getTypeById(type);
    }

    /**
     * 通过楼栋id查询设备信息
     */
    @GetMapping("/getBuildById/{id}")
    public List<Device> getBuildById(@PathVariable("id") Integer id){
        return deviceService.getBuildById(id);
    }

    /**
     * 通过楼层id查询设备信息
     */
    @GetMapping("/getFloorById/{id}")
    public List<Device> getFloorById(@PathVariable("id") Integer id){
        return deviceService.getFloorById(id);
    }

    /** 熔断降级 */
    public JSONResult fuseDegradation(Integer id){
        return new JSONResult(false,"熔断了！");
    }

    /** 限流 */
    public JSONResult degradationMethod(Integer id){
        return new JSONResult(false,"流控了！");
    }

}
